#!/bin/bash

# AOW2 build script for Linux by Dusk

# It takes one optional argument, an alternate destination path, meaning that
# calling for instance "./build.sh ~/doom" will build omega_data_*.pk3 directly
# into ~/doom instead

# =============================================================================

# Determine where to build
if [ -z $1 ]; then
	dest=$(pwd)
else
	if [ ! -d $1 ]; then
		echo "$1: no such directory"
		dest=$(pwd)
	elif [ ! -w $1 ]; then
		echo "$1 is not writable."
		dest=$(pwd)
	else
		dest="$1"
	fi
fi

# Check that our environment is good
echo "Checking environment... "

# Check permissions
if [ ! -w ".." ]; then
	echo "ERROR: parent directory not writable"
	exit 5
fi

# Check svn
if [ -z $(which acc) ]; then
	echo "ERROR: no acc in PATH"
	exit 1
fi

# Check svnversion
if [ -z $(which svn) -o -z $(which svnversion) ]; then
	echo "ERROR: no svn and/or svnversion in PATH"
	exit 1
fi

# Check zip
if [ -z $(which zip) ]; then
	echo "ERROR: no zip in PATH?!"
	exit 1
fi

# Get filename. M is added automatically
rev=$(svnversion)
fn="thenewmod_r$rev.pk3"

# Must not be exported.
if [ "$rev" == "exported" ]; then
	echo "ERROR: this is no SVN directory!"
	exit 2
fi

# src/ must exist. This shouldn't happen..
if [ ! -d "./src" ]; then
	echo "ERROR: no such directory \`./src'"
	exit 3
fi

# ../temp already exists!
if [ -d "./temp" ]; then
	echo "./temp must not exist in order to build. Delete it? (y/n)"
	rm -rI ./temp # Delete it but ask the user first
	
	if [ -d "../temp" ]; then
		# If it still exists, the user chose not delete it
		exit 4
	fi
fi

echo "Environment OK. Going to build revision $rev."

# First, compile the ACS.
if [ ! -d "./build/acs_compile" ]; then
	mkdir -pv ./build/acs_compile
fi

pushd ./build/acs_compile >/dev/null
acc -I ../../utils/acc ../../src/acs_src/a_main.acs a_main.o
acc -I ../../utils/acc ../../src/acs_src/a_mapcfg.acs a_mapcfg.o

if [ ! -f a_main.o -o ! -f a_mapcfg.o ]; then
	echo "ERROR: ACS did not compile properly."
	exit 5
fi

cd ..

# Export it
echo -n "Exporting... "

if [ -d pk3build ]; then
	rm -rf pk3build
fi

svn export ../src pk3build >/dev/null
if [ $? -ne 0 ]; then
	echo "Export failed."
	exit 1
fi

echo "done"

cd pk3build

echo -n "Adding compiled ACS... "
mkdir acs/
mv ../acs_compile/a_main.o acs/
mv ../acs_compile/a_mapcfg.o acs/
echo "done"

echo -n "Creating archive $fn... "
zip -r -1 $fn * >/dev/null

if [ $? -ne 0 ]; then
	echo "ERROR: Archive did not build properly."
	exit 1
fi

echo "done"

echo -n "Moving $fn... "
mv $fn $dest
if [ $? -ne 0 ]; then
	echo "Something went wrong with file moving. Retrieve the archive from temp directory and remove temp afterwards."
	exit 1
fi

echo "done"

echo -n "Clearing build directory... "
cd ../.. && rm -rf build
echo "done"

echo "Finished!"
